import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2025-07-15
 * Time: 22:14
 */
public class Test53 {
    static int[] dx = {1,-1,0,0};
    static int[] dy = {0,0,1,-1};
    static int m;
    static int n;
    static boolean[][] vis;
    public static int orangesRotting(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        int ret = 0;
        Queue<int[]> q = new LinkedList<>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 2) {
                    q.offer(new int[]{i,j});
                }
            }
        }

        while(!q.isEmpty()) {
            int size = q.size();
            for(int i = 0; i < size; i++) {
                int[] t = q.poll();
                int a = t[0], b = t[1];
                for(int k = 0; k < 4; k++) {
                    int x = a+dx[k],y = b+dy[k];
                    if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
                        grid[x][y] = 2;
                        q.offer(new int[]{x,y});
                    }
                }
            }
            ret++;
        }

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    return -1;
                }
            }
        }
        return ret == 0 ? 0 : ret-1;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n1 = sc.nextInt();
        int n2 = sc.nextInt();
        int[][] num = new int[n1][n2];
        for(int i = 0; i < n1; i++) {
            for(int j = 0; j < n2; j++) {
                num[i][j] = sc.nextInt();
            }
        }
        int ret = orangesRotting(num);
        System.out.println(ret);
    }
}
